//
//  PHAsset+AssetImage.m
//  Logistics
//
//  Created by 刘峰 on 2018/1/12.
//  Copyright © 2018年 com.Logistics. All rights reserved.
//

#import "PHAsset+AssetImage.h"

@implementation PHAsset (AssetImage)

+ (void)getOriginalImagesWithAssets:(NSArray *)assets                          AssetBlock:(AssetImageBlock)block {
    
    NSMutableArray *images = [NSMutableArray array];

    PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
    option.networkAccessAllowed = YES;
    option.synchronous = YES;
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
       
        for (PHAsset *asset in assets) {
            
            [[PHCachingImageManager defaultManager] requestImageForAsset:asset targetSize:CGSizeMake(asset.pixelWidth, asset.pixelHeight) contentMode:PHImageContentModeDefault options:option resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                [images addObject:result];
                if (images.count == assets.count) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (block) {
                            block(images);
                        }
                    });
                }
            }];
        }
        
    });
    
}


- (void)getOriginalImageLoadedBlock:(AssetAlongBlock)block {
    PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
    option.networkAccessAllowed = YES;
    option.synchronous = YES;

    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [[PHCachingImageManager defaultManager] requestImageForAsset:self targetSize:CGSizeMake(self.pixelWidth, self.pixelHeight) contentMode:PHImageContentModeDefault options:option resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            if (block) {
                block(result);
            }
        }];
    });
}

- (void)getOriginalImageFromIClound:(AssetLoadedBlock)block {
    PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
    option.networkAccessAllowed = YES;
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [[PHCachingImageManager defaultManager] requestImageForAsset:self targetSize:CGSizeMake(self.pixelWidth, self.pixelHeight) contentMode:PHImageContentModeDefault options:option resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
            if (block) {
                block(result, ![info[PHImageResultIsDegradedKey] boolValue]);
            }
        }];
    });
}



- (void)getThumbImageWithiMageSize:(CGSize)imageSize
                        AssetBlock:(AssetAlongBlock)block {
    
    [[PHCachingImageManager defaultManager] requestImageForAsset:self targetSize:imageSize contentMode:PHImageContentModeDefault options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
        if (block) {
            block(result);
        }
    }];
}

@end
